﻿using System;
using System.Data;
using System.Configuration;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Reflection;
using System.IO;
using System.Text;
using System.Threading;

namespace TA.Turbo.Controls
{
	/// <summary>
	/// Base class for all includes from embedded resources.
	/// </summary>
	public abstract class BaseResourceInclude : BaseInclude
	{
		#region PUBLIC
		#region INIT
		/// <summary>
		/// Ctor.
		/// </summary>
		public BaseResourceInclude()
		{
			//
			// TODO: Add constructor logic here
			//

		}
		#endregion
		#region PROPS
		/// <summary>
		/// Gets or sets the type which will be used to get the assembly from which to load the resource.
		/// </summary>
		public Type Type { get; set; }
		/// <summary>
		/// The name of the embedded resource.
		/// </summary>
		public string Resource { get; set; }
		/// <summary>
		/// Gets the contents of the embedded resource.
		/// </summary>
		public override string Content
		{
			get
			{
				if (_content == null)
				{
					if (Type != null)
					{
						string cacheKey = "TA.Turbo.BaseResourceInclude." + Type.Assembly.FullName + Resource;
						if (HttpContext.Current.Cache[cacheKey] == null)
						{
							Stream stream = Type.Assembly.GetManifestResourceStream(Resource);
							if (stream != null)
							{
								byte[] buf = new byte[stream.Length];
								stream.Read(buf, 0, (int)stream.Length);
								_content = Encoding.UTF8.GetString(buf);

								stream.Close();
							}
							if (_content == null)
								throw new InvalidOperationException("Resource '" + this.Resource + "' failed to load.");
							HttpContext.Current.Cache[cacheKey] = _content;
						}
						_content = (string)HttpContext.Current.Cache[cacheKey];
					}
				}
				return _content;
			}
		}
		/// <summary>
		/// Gets the name of the resource.
		/// </summary>
		public override string FileName
		{
			get
			{
				return Resource;
			}
		}
		#endregion
		#region JSON
		#endregion
		#endregion
		#region INTERNAL
		#region VARS
		string _content;
		#endregion
		#endregion

	}
}